package com.yzy.loader
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	public class DataLoader extends EventDispatcher
	{
		
		private static var dataLoader:URLLoader; 

		public function DataLoader(){}
		
		/**
		 * loader data
		 * @param url:String
		 * @param dataType:URLLoaderDataFormat.BINARY or URLLoaderDataFormat.TEXT
		 * @param completeFun: completeFun(dataLoader.data)
		 * @param progressFun: progressFun(event.bytesTotal,event.bytesLoaded);
		 * //Example//
		 * DataLoader.loaderData("sd11x5.txt",loaderComplete,loaderProgress,URLLoaderDataFormat.TEXT);
		 * private function loaderComplete(data:String):void{}
		 * private function loaderProgress(bytesTotal:Number,bytesLoaded:Number):void{}  
		 */		
		public static function loaderData(url:String,completeFun:Function,progressFun:Function,dataType:String=URLLoaderDataFormat.BINARY):void{
			var request:URLRequest=new URLRequest(url);
			dataLoader=new URLLoader();
//			var loadercontext:LoaderContext=new LoaderContext();
//			loadercontext.allowCodeImport=true;
			dataLoader.dataFormat=dataType;
			dataLoader.addEventListener(IOErrorEvent.IO_ERROR,loaderIOError);
			dataLoader.addEventListener(ProgressEvent.PROGRESS,function loaderProgress(evt:ProgressEvent):void{
				progressFun(evt.bytesTotal,evt.bytesLoaded);
			});
			dataLoader.addEventListener(Event.COMPLETE,function dataLoaderComplete(evt:Event):void{
				dataLoader.removeEventListener(Event.COMPLETE,dataLoaderComplete);
				dataLoader.close();
				completeFun(dataLoader.data);
			});
			dataLoader.load(request);
			
		}
		
		protected static function loaderIOError(event:IOErrorEvent):void
		{
			trace("error="+event.toString());
		}	
	}
}